<?php

namespace app\api\controller\v2;

use app\api\model\Attention;
use app\api\model\Blacklist;
use app\api\model\ConfigPersonal;
use app\api\model\DymanicCategory;
use app\api\model\DymanicUserlover;
use app\api\model\DymanicUserthumbsup;
use app\api\model\LabelsUser;
use app\api\model\UserActiveval;
use think\Db;
use think\Request;
use app\api\model\Dymanic as DymanicModel;
use app\api\model\ConfigSystem as Config;
use app\api\model\Labels;
use app\api\model\User;
use app\api\model\OrderCommon as Order;
use GatewayClient\Gateway;
use app\api\controller\Common;

class Dymanic extends Common
{
    public $params = null;
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->params = getRsaPostParamArr2();
    }
    public function lists()
    {
        // var_dump($this->MIXparams);exit;
        $type = $this->params['type'] ?? 0;
        $readed = $this->params['readed'] ?? 0;
        $zaned = $this->params['zaned'] ?? 0;
        $lover = $this->params['lover'] ?? 0;
        $class = $this->params['class'] ?? 0;
        $category_id = $this->params['category_id'] ?? '';
        $topic = $this->params['topic'] ?? '';
        $video = $this->params['video'] ?? 0;
        $authed = $this->params['authed'] ?? 0;
        $group_id = $this->params['group_id'] ?? 0;
        $privacy = $this->params['privacy'] ?? 0;
        $userid_privacy = 0;
        $source_type = $this->params['source_type'] ?? '';

        if (!$this->member || $this->member['reg'] == 0) {
            $video = $this->params['video'] = -1;
        }

        $this->params['userid'] = $this->params['userid'] ?? '';
        $this->params['following'] = $this->params['following'] ?? '';
        $this->params['citys'] = $this->params['citys'] ?? '';
        $this->params['slide'] = $this->params['slide'] ?? '';
        $this->params['shang'] = $this->params['shang'] ?? '';
        $this->params['sort'] = $this->params['sort'] ?? '';
        $this->params['keyword'] = $this->params['keyword'] ?? '';
        $this->params['longitude'] = $this->params['longitude'] ?? '';
        $this->params['latitude'] = $this->params['latitude'] ?? '';
        $page = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 10;

        $fetchsql = 0;

        
        $where = "shenhe = 1 and type <= 1 and private = 0";
        $order = '';
        //此处判断用户有无邀请人，无邀请人的只显示无邀请人的动态
        $dquser=$this->params['user_id'];
        $userinfo=Db::name('user')->where(['id'=>$dquser])->find();
        if ($userinfo && empty($userinfo['yqr'])) {//无邀请人
            $wyqusers = Db::name('user')->where(['yqr'=>''])->column('id');
            $where .= " and userid in (" . implode(',', $wyqusers) . ")";
        }
        
        if ($privacy) {
            $this->member = Db::name('user')->where(['authcode'=>$this->member['id'], 'reg'=>2])->find();
            $where .= ' and source_type=6';
        }

        $blacklist = Blacklist::lists($this->member['id'], true);

        if ($source_type) {
            $where .= ' and source_type='.$source_type;
        }

        if ($video) {
            if ($video == -1) {
                $where .= " and dymanic.video = ''";
                if ($page > 1) {
                    return $this->pass([]);
                }
            } else {
                $infos = Db::name('dymanic')->where(['dy_id'=>$video])->find();
                if ($infos) {
                    $where .= " and dy_id <> " . $video . " and dymanic.video <> '' and source_type=0";
                    $cate_childrens = $infos['cate_children'];
                    if ($cate_childrens) {
                        $cate_childrens = explode(',', $cate_childrens);
                        $cate_childrens_where = [];
                        foreach ($cate_childrens as $cate_key => $cate_val) {
                            $cate_childrens_where[] = "find_in_set($cate_val,cate_children)";
                        }
                        if (sizeof($cate_childrens_where)) {
                            $where .= ' and (' . implode(' or ', $cate_childrens_where) . ')';
                            $class = 0;
                        }
                    } else if ($infos['category_id']) {
                        $category_id = $infos['category_id'];
                    }
                }
            }
        }

        $unionWhere = '';
        if ($type) {
            switch ($type) {
                case 1:
                    $unionWhere .= ' and masterimg="" and video=""';
                    break;
                case 3:
                    $unionWhere .= ' and video<>""';
                    break;
                case 4:
                    $unionWhere .= ' and masterimg<>"" and video=""';
                    break;
                
                default:
                    break;
            }
            $where .= $unionWhere;
        }

        if ($authed) {
            $unionWhere .= ' and class=2';
            $where .= ' and class=2';
        }

        $blacklistwhere = $blacklist ? " and id not in ($blacklist)" : "";
    
        $extends = [];
        if ($this->params['keyword']) {
            if ($authed) {
                $where .= " and topic_experience <> '' and (content like '%" . $this->params['keyword'] . "%' or topic_experience like '%" . $this->params['keyword'] . "%')";
            } else {
                $where .= " and (content like '%" . $this->params['keyword'] . "%' or title like '%" . $this->params['keyword'] . "%')";
            }
            $extends = $this->extendFunction($this->params['keyword'], 1, 5, false);
        }
        
        if ($this->params['userid']) {
            $where .= " and dymanic.state = 0 and dymanic.userid = " . $this->params['userid'];
        } else if (!$readed && !$zaned && !$lover && !$this->params['keyword'] && !$this->params['following'] && !$category_id && !$topic && $class) {
            $where .= " and class=".$class;
        }

        $topic_visit_count = 0;
        if ($topic) {
            if ($authed) {
                $where .= " and (topic_experience like '%&" . $topic . "' or topic_experience like '%&" . $topic . " &%')";
                $topic_visit_count = Db::name('dymanic')->where("shenhe = 1 and (topic_experience like '%&" . $topic . "' or topic_experience like '%&" . $topic . " &%')")->sum('visit');
            } else {
                $where .= " and (topic like '%#" . $topic . "' or topic like '%#" . $topic . "#%')";
                $topic_visit_count = Db::name('dymanic')->where("shenhe = 1 and (topic like '%#" . $topic . "' or topic like '%#" . $topic . "#%')")->sum('visit');
            }
        }

        if ($this->params['citys']) {
            $where .= " and citys like '%" . $this->params['citys'] . "%'";
        }
        
        $userwheresex = '';
        
        if ($category_id) {
            $where .= " and category_id = " . $category_id;
        }
        
        if ($this->params['following']) {
            $attention = Attention::lists($this->member['id']);
            
            $blacklist = explode(',', $blacklist);
            
            $attention_str = implode(',', array_diff($attention, $blacklist));
            
            $attention_str = $attention_str ?: 0;
            
            $where .= " and dymanic.userid in ($attention_str)";
        } else if ($this->member) {
            if (!$privacy) {
                $where .= ' and ((dymanic.userid = '.$this->member['id'].' and dymanic.addway=2) or dymanic.userid <> '.$this->member['id'].')';
            }
        }
    
        $whereOr = $where;
    
        $mine = false;
        if ($this->params['slide']) {
            $type = 1;
            
            $where .= " and type = 1 and masterimg <> ''";
            $order = "sort desc, visit desc, $order";
        
            $whereOr = $where;
        } else {
            $where_sex = $this->member['sex'] == '男' ? '女' : '男';
            // if ($type != 1 && input('wheresex', 1)) {
            if (!$category_id) {
                $userwheresex = "sex = '" . $where_sex . "' and";
                if (in_array($this->member['entertainment'], [0,2,3])) {
                    $userwheresex .= " entertainment in (0,2,3) and age between ".($this->member['age']-10)." and ".($this->member['age']+10)." and";
                } else {
                    $userwheresex .= " entertainment = 1 and age between ".($this->member['age']-10)." and ".($this->member['age']+10)." and";
                }
            }
            
            if ($this->params['userid'] && $this->params['user_id'] == $this->params['userid']) {
                $userid_privacy = Db::name('user')->where(['authcode'=>$this->member['id'], 'reg'=>2])->value('id');
                $mine = true;
            }
        }

        if ($group_id) {
            $groupUserids = Db::name('share_group_join')->where(['state'=>1,'group_id'=>$group_id])->column('user_id');
            $groupUserids = Db::name('user')->where(['delete_time'=>0, 'id'=>['in',$groupUserids]])->column('id');
            if (empty($groupUserids)) {
                return $this->pass([], 'data', ['count'=>0]);
            }
            $where .= ' and dymanic.userid in ('.implode(',', $groupUserids).')';
        }

        if ($this->params['shang']) {
            $userwheresex = "sex = '男' and";
        }

        $union = "";
        $join = "";
        if (!$this->params['following']) {
            if($mine && $this->params['userid']){
                $where .= ' and addway=2';
                $unionWhere .= ' and addway=2';
                if ($userid_privacy) {
                    $union = "union select * from dymanic where type=".$type." and state = 0 and shenhe < 2 and userid in ($userid_privacy," . $this->params['userid'] . ")" . $unionWhere;
                } else {
                    $union = "union select * from dymanic where type=".$type." and state = 0 and shenhe < 2 and userid=" . $this->params['userid'] . $unionWhere;
                }
            } else {
                $join = 'left join user on dymanic.userid=user.id and user.entertainment>0';
                if ($this->member['age'] && $category_id === '0' && !$video) {
                    $where .= " and user.age between " . ($this->member['age'] - 20) . " and " . ($this->member['sex'] == '女' ? $this->member['age'] + 20 : $this->member['age'] + 3);
                }

                $sexSet = $this->member['sex'] == '男' ? '女' : '男';
                $where .= ($this->member['sex'] == '男' ? ' and see_limit in (2,3)' : ' and see_limit in (1,3)');
                $entertainment = $this->params['entertainment'] ?? '';
                if ($entertainment || $entertainment === '0') {
                    $where .= ' and user.entertainment='.$entertainment .' and user.sex="'.$sexSet.'"';
                }

                if ($readed) {
                    $join .= ' inner join dymanic_read on dymanic.dy_id=dymanic_read.dy_id';
                    $where .= ' and dymanic_read.userid='.$this->member['id'];
                }

                if ($zaned) {
                    $join .= ' inner join dymanic_userthumbsup on dymanic.dy_id=dymanic_userthumbsup.dy_id';
                    $where .= ' and dymanic_userthumbsup.userid='.$this->member['id'];
                }

                if ($lover) {
                    $join .= ' inner join dymanic_userlover on dymanic.dy_id=dymanic_userlover.dy_id';
                    $where .= ' and dymanic_userlover.userid='.$this->member['id'];
                }

            }
        }


        $startPage = ($page - 1) * $pagesize;

        // 排序
        switch ($this->params['sort']) {
            case 'hot':
                $order = 'liveness desc' . ($order ? ','. $order : '');
                break;
            case 'new':
                $order = 'dy_id desc' . ($order ? ','. $order : '');
                break;
            default:
                $order = 'top desc, dy_id desc';
                break;
        }

        if ($category_id === '0' && !$video && !$privacy && !$source_type) {
            $order = 'liveness desc, dy_id desc';
            if ($page == 1) {
                cache('dylists:offset:'.$this->member['id'], rand(0,30), 600);
            }
            $offset = cache('dylists:offset:'.$this->member['id']) ?? 0;
            $startPage += $offset;
        }

        if ($readed) {
            $order = 'dymanic_read.id desc';
        } else if ($zaned) {
            $order = 'dymanic_userthumbsup.id desc';
        } elseif ($lover) {
            $order = 'dymanic_userlover.time desc';
        } elseif ($this->params['citys']) {
            $order = 'RAND()';
        }
        
        
        // var_dump($order);exit;

        
        $fielduser = 'id, head_100 avatar, nvshen, kejian, name, age, sex,
            is_identity_authentication, attestation, constellation, noble_grade, noble_time, xuni_discount, hide_distance,
            register_datetime, realname_auth, longitude, latitude, real_avatar, auth_tag';
        $field = 'dymanic.*';
        if ($readed) {
            $field .= ',dymanic_read.id';
            $sql = "select * from (select $field from dymanic $join where $where $union order by $order) a GROUP BY dy_id ORDER BY id desc limit $startPage, $pagesize";
            $CountSql = "select count(dymanic.dy_id) count from (select dymanic.dy_id from dymanic $join where $where $union group by dy_id) dymanic";
        } else {
            $sql = "select $field from dymanic $join where $where $union order by $order limit $startPage, $pagesize";
            $CountSql = "select count(dymanic.dy_id) count from dymanic $join where $where $union";
        }
        if ($union) {
            $CountSql = str_replace('*', 'count(dymanic.dy_id) count', $CountSql);
        }

        if ($fetchsql) {
            var_dump($sql);exit;
        }
        
        // file_put_contents(
        //     "./log.txt",           // 日志文件路径，如 logs/runtime.log
        //     $sql. PHP_EOL,  // 日志内容（带时间戳），例如：[2025-05-23 14:00:00] 部署成功
        //     FILE_APPEND                // 文件写入模式，追加到已有内容后面
        // );
        // $cacheKey = 'v2dylistsql'.md5($sql);
        // $cacheKey2 = 'v2dycountsql'.md5($CountSql);
        // $data = cache($cacheKey);
        // $count = cache($cacheKey2);
        // if (!$data) {
            $data = Db::query($sql);
            $count = Db::query($CountSql);
            // cache($cacheKey, $data, 60);
            // cache($cacheKey2, $count, 60);
        // }
        $count = $count[0]['count'];

        // var_dump($data);exit;

        if ($data) {
            $start = strtotime(date("Ymd"));
    
            $loves = DymanicUserlover::where(['userid' => $this->member['id']])->column('dy_id');
            $thumbsups = DymanicUserthumbsup::where(['userid' => $this->member['id']])->column('dy_id');
            $attentions = Db::name('attention')->where(['user_id' => $this->member['id'], 'sys_channel' => 1])->column('to_user');
            $category = DymanicCategory::where(['id' => ['gt', 0]])->column('id, name');
    
            if ($type == 1) {
                $ids = array_column($data, 'to_user');
        
                $users = User::where(['id' => ['in', $ids]])->column('id, name, head_100 avatar');
            }
    
            $ids = array_column($data, 'userid');
            $personals = ConfigPersonal::where(['user_id' => ['in', $ids]])->column('user_id, id, hide_distance');
    
            $config = Config::where(['category' => 'user'])->column('title, content');
            $dyusers = Db::name('user')->where(['id'=>['in', array_column($data, 'userid')]])->column($fielduser, 'id');
            $returnData = [];



            $extend_func_ids = array_filter(array_unique(array_column($data, 'extend_func_id')));
            if (sizeof($extend_func_ids)) {
                $extend_funcs = Db::name('extend_function')->where(['id'=>['in', $extend_func_ids]])->column('id,name,icon,path', 'id');
            } else {
                $extend_funcs = [];
            }
            
            foreach ($data as $key => $item) {
                if(!isset($dyusers[$item['userid']])){
                    continue;
                }
                $dyuser = $dyusers[$item['userid']];
                $item = array_merge($item, $dyuser);
                $data[$key]['id'] = $item['id'];
                //新增
                $data[$key]['sex']=$item['sex'] ?? '';
                $data[$key]['age']=$item['age'] ?? '';
                
                if($item['extend_func_id']) {
                    $data[$key]['extend_func_info'] = $extend_funcs[$item['extend_func_id']] ?? false;
                }

                // if (isset($personals[$item['userid']]['hide_distance']) && $personals[$item['userid']]['hide_distance']) {
                //     $data[$key]['citys'] = '';
                // }
                
                $data[$key]['name'] = $item['name'] ?? '';
                // $data[$key]['avatar'] = isset($item['avatar']) && $item['avatar'] ? changeUrl($item['avatar']) . '?x-oss-process=image/resize,w_100/quality,q_50' : '';
                $data[$key]['avatar'] = isset($item['avatar']) && $item['avatar'] ? changeUrl($item['avatar']) : '';
                try {
                    $data[$key]['is_vip'] = $item['noble_grade'] && $item['noble_time'] > time() ? 1 : 0;
                    $data[$key]['is_new'] = $item['register_datetime'] && (strtotime($item['register_datetime']) + 86400) > time() ? 1 : 0;
                } catch (\Exception $e) {
                    $data[$key]['is_new'] = 0;
                    $data[$key]['is_vip'] = 0;
                }
                $data[$key]['auth_tag'] = $item['auth_tag'];
                $data[$key]['overdue'] = $start > strtotime($item['addtime']) ? 1 : 0;
                $data[$key]['is_attention'] = in_array($item['userid'], $attentions) ? 1 : 0;
                $data[$key]['isthumbsup'] = in_array($item['dy_id'], $thumbsups) ? 1 : 0;
                $data[$key]['islover'] = in_array($item['dy_id'], $loves) ? 1 : 0;
                $data[$key]['real_avatar'] = $item['real_avatar'] ?? '';
    
                if(intval($item['xuni_discount'] ?? 0)){
                    $distance = $item['xuni_discount'];
                }else{
                    $distance = _distance($item['longitude'], $item['latitude'], floatval($this->params['longitude']), floatval($this->params['latitude']));
                }
                $data[$key]['distance'] = $item['hide_distance'] ? '保密' : ($distance >= 1000 ? number_format(($distance / 1000), 1) . 'km' : number_format($distance, 1) . 'm');
    
                // if ($config['hide_city'] && $item['sex'] == '女') {
                //     $data[$key]['citys'] = '';
                // }
    
                $masterimg = explode(",", $item['masterimg']);
                $masterimg = array_unique(array_filter($masterimg));
                foreach ($masterimg as $m => $n) {
                    $masterimg[$m] = changeUrl($n) . '?x-oss-process=image/resize,w_400/quality,q_70';
                }
                $data[$key]['masterimg'] = $masterimg;

                $sumbImage = explode(",", $item['sumbImage']);
                $sumbImage = array_unique(array_filter($sumbImage));
                foreach ($sumbImage as $m => $n) {
                    $sumbImage[$m] = changeUrl($n) . '?x-oss-process=image/resize,w_400/quality,q_70';
                }
                $data[$key]['sumbImage'] = $sumbImage;
    
                switch ((int)$item['source_type']) {
                    case 1:
                        $data[$key]['source_info'] = action('api/flag/flagsInfo', ['flags_id'=>$item['source_id'], 'returnJson'=>false]);
                        break;
                    case 3:
                        $data[$key]['source_info'] = Db::name('user_service')->where(['id'=>$item['source_id']])->field('title,price,image,method')->find();
                        break;
                    case 4:
                        $source_info = Db::name('activity_offline')->where(['id'=>$item['source_id']])->field('address_name,sex,pay,price,content,images')->find();
                        if ($source_info && $source_info['images']) {
                            $source_info['images'] = explode(',', $source_info['images']);
                        }
                        $data[$key]['source_info'] = $source_info;
                        break;
                }
                $data[$key]['commentList'] = Db::name('dycomment')->where(['dy_id'=>$item['dy_id'], 'shenhe'=>1])->limit(3)->order('comment_id desc')->field('userid,content')->select();
                if (sizeof($data[$key]['commentList'])) {
                    foreach ($data[$key]['commentList'] as &$val) {
                        $val['user'] = _user_cache($val['userid']);
                    }
                }
                $data[$key]['thumbsup'] += $item['xuni_thumbsup'];
                unset($data[$key]['xuni_thumbsup']);


                if ($data[$key]['topic']) {
                    $topic = explode('#',$data[$key]['topic']);
                    $data[$key]['topic'] = [];
                    foreach ($topic as &$v) {
                        if ($v) $data[$key]['topic'][] = $v;
                    }
                } else {
                    $data[$key]['topic'] = [];
                }

                if ($data[$key]['topic_experience']) {
                    $topic_experience = array_filter(explode('&',$data[$key]['topic_experience']));
                    $data[$key]['topic_experience'] = [];
                    foreach ($topic_experience as &$v) {
                        $data[$key]['topic_experience'][] = $v;
                    }
                } else {
                    $data[$key]['topic_experience'] = [];
                }


                $data[$key]['price'] *= getenv('APP_RATE');
                if ($data[$key]['class'] == 2 && $data[$key]['userid'] != $this->member['id']) {
                    $data[$key]['paystate'] = Db::name('order_of_subscribe')->where(['user_id'=>$this->member['id'], 'dy_id'=>$data[$key]['dy_id']])->count();
                } else {
                    $data[$key]['paystate'] = 1;
                }

                if ($item['video'] && $item['enroll']) {
                    $data[$key]['video'] = changeUrl($item['video'], 1);
                }

                $returnData[] = $data[$key];
            }
        } else {
            $returnData = [];
        }


        if ($this->params['keyword']) {
            $has = Db::name('search_history')->where(['content' => $this->params['keyword']])->find();
            if ($has) {
                Db::name('search_history')->where(['id' => $has['id']])->update(['time' => time(), 'result' => sizeof($returnData)]);
            } else {
                Db::name('search_history')->insert(['user_id' => $this->member['id'], 'content' => $this->params['keyword'], 'time' => time(), 'result' => sizeof($returnData)]);
            }
        }
        
        return $this->pass($returnData, 'data', compact('extends', 'topic_visit_count', 'count'));
    }



    public function extendFunction($keyword = '', $page = 1, $pagesize = 20, $returnJson = true)
    {
        $extendWhere = [
            'is_hidden' => 0,
            'name'  => ['like', $keyword . '%'],
        ];
        $extend = Db::name('extend_function')
            ->where($extendWhere)
            ->page($page)
            ->limit($pagesize)
            ->field('id,name,icon,description,path')
            ->order('sort desc, id asc')
            ->select();
        return $returnJson ? $this->pass($extend) : $extend;
    }


    public function record()
    {
        if (!$this->member) return $this->pass('');
        $dy_id = $this->params['dy_id'] ?? 0;
        $start_time = $this->params['start_time'] ?? 0;
        $end_time = $this->params['end_time'] ?? 0;
        $play_time = $this->params['play_time'] ?? 0;

        $dymanic = Db::name('dymanic')->where([
            'dy_id' => $dy_id,
            'shenhe' => 1
        ])->find();

        if (!$dymanic) return $this->pass('');

        Db::name('dymanic')->where(['dy_id' => $dy_id])->setInc('visit');

        // $record = Db::name('dymanic_read')->where(['dy_id' => $dy_id, 'userid'=>$this->member['id']])->find();
        // if ($record) {
        //     Db::name('dymanic_read')->where(['id' => $record['id']])->update(['time'=>datetime()]);
        // } else {
            Db::name('dymanic_read')->insert(['dy_id' => $dy_id, 'userid'=>$this->member['id']]);
        // }

        return $this->pass('');
    }
}